/* eslint-disable */
<template>
  <a-modal
    :visible="visible"
    :width="900"
    :mask-closable="false"
    @ok="handleModalOk"
    :hideCancel="true"
    @cancel="handleCancel"
  >
    <template #title> 地图 </template>
    <div class="inputWrapper">
      <a-select
        v-model="selectVal"
        placeholder="请输入位置关键字"
        @search="handleSearch"
        :loading="loading"
        :filter-option="false"
        allow-search
      >
        <a-option
          @click="handleChange(item.id)"
          v-for="item in addressList"
          :key="item.id"
          :value="item.id"
          >{{ item.name }}</a-option
        >
      </a-select>
    </div>

    <div id="txMapContainer"></div>
  </a-modal>
</template>

<script setup>
// import AMapLoader from '@amap/amap-jsapi-loader';
import { ref, watch, onMounted, getCurrentInstance, toRaw } from 'vue';

const { proxy } = getCurrentInstance();
const emits = defineEmits(['confrimHandler', 'update:modelValue']);

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: () => false,
  },
  lnglat: {
    type: Array,
    default: () => [],
  },
});

const selectVal = ref('');
const addressList = ref([]);

const allMarker = ref([]);

let map = null;

const loading = ref(false);

let timer = null;

const visible = ref(false);


const multiple = ref(true);

watch(
  () => props.modelValue,
  n => {
    visible.value = n;
  }
);
let autoComplete = null;

const searchListByInput = val => {
  autoComplete.search(val, (status, result) => {
    loading.value = false;
    // 搜索成功时，result即是对应的匹配数据
    addressList.value = (result.tips || []).filter(v => v.id && v.location);
  });
};

const handleSearch = val => {
  multiple.value = false;
  addressList.value = [];
  clearTimeout(timer);
  timer = setTimeout(() => {
    loading.value = true;
    searchListByInput(val);
  }, 200);
};

const addressInfo = ref({});

let Geocoder = null;


const clearRecord = () => {
  selectVal.value = '';
  addressList.value = [];
  map.remove(allMarker.value);
};

const handleCancel = () => {
  emits('update:modelValue', false);
};

const handleChange = val => {
  addressInfo.value = addressList.value.find(v => v.id === val);

  console.log(addressInfo.value);

  map.setZoomAndCenter(16, [
    addressInfo.value.location.lng,
    addressInfo.value.location.lat,
  ]);

  map.remove(allMarker.value);
  allMarker.value = [];
  const marker = new AMap.Marker({ // eslint-disable-line
    position: new AMap.LngLat( // eslint-disable-line
      addressInfo.value.location.lng,
      addressInfo.value.location.lat
    ), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
    title: addressInfo.value.address,
  });
  allMarker.value.push(marker);
  map.add(marker);
};

const handleModalOk = () => {
  emits('confrimHandler', toRaw(addressInfo.value));
};

const initDafaultAddress = () => {
  if (props.lnglat.length > 0 && props.lnglat[0]) {
    Geocoder.getAddress(props.lnglat, (status, result) => {
      if (status === 'complete' && result.regeocode) {
        const time = new Date().getTime();
        addressList.value = [
          {
            id: time,
            name: result.regeocode.formattedAddress,
            district: result.regeocode.formattedAddress,
            address: '',
            adcode: result.regeocode.addressComponent.adcode,
            location: {
              lat: props.lnglat[1],
              lng: props.lnglat[0],
            },
          },
        ];
        selectVal.value = time;
        handleChange(time);
      }
    });
  } else {
    map.remove(allMarker.value);
  }
};

const mapClickHandler = () => {
  map.on('click', ev => {
    Geocoder.getAddress([ev.lnglat.lng, ev.lnglat.lat], (status, result) => {
      if (status === 'complete' && result.regeocode) {
        const time = new Date().getTime();
        addressList.value = [
          {
            id: time,
            name: result.regeocode.formattedAddress,
            district: result.regeocode.formattedAddress,
            address: '',
            adcode: result.regeocode.addressComponent.adcode,
            location: {
              lat: ev.lnglat.lat,
              lng: ev.lnglat.lng,
            },
          },
        ];
        selectVal.value = time;
        handleChange(time);
      }
    });
  });
};

const initHandler = () => {
  // window._AMapSecurityConfig = {
  //   securityJsCode: '0e074877d75e6478a8645c83d02f3f9e',
  // };

  // AMapLoader.load({
  //   key: '322a534b82c08fdb1887893a183ec424', // 申请好的Web端开发者Key，首次调用 load 时必填
  //   version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
  // })
  //   .then(AMap => {
  map = new AMap.Map('txMapContainer', { // eslint-disable-line
    zoom: 16,
    animateEnable: false,
    center: [117.022086, 36.661373], // 初始化地图中心点位置
  });

  // AMap.plugin('AMap.Geocoder', () => {
  const autoOptions = {
    // city 限定城市，默认全国
    // radius: '1000',
  };
  // 实例化AutoComplete
  Geocoder = new AMap.Geocoder(autoOptions); // eslint-disable-line

  initDafaultAddress();
  // });

  // AMap.plugin('AMap.AutoComplete', () => {
  // 实例化AutoComplete
  autoComplete = new AMap.AutoComplete(autoOptions); // eslint-disable-line
  // });

  mapClickHandler();
};

onMounted(() => {
  proxy.$nextTick(() => {
    initHandler();
  });
});

defineExpose({
  clearRecord,
  initHandler
});
</script>

<style lang="less" scoped>
.inputWrapper {
  margin-bottom: 20px;
}
#txMapContainer {
  width: 100%;
  height: 400px;
}
</style>
